package com.hyfrogx.modules.sign.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyfrogx.common.qcloud.UploadUtils;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.modules.app.service.IntegralConfigService;
import com.hyfrogx.modules.app.utils.FrogConstant;
import com.hyfrogx.modules.sign.entity.IntegralConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 积分配置规则
 * @author liubin
 * @date 2019/12/5 10:21
 */
@RestController
@RequestMapping("integral/config")
@Api(value = "IntegralController", tags = {"后台--积分配置"})
public class IntegralController {

  @Autowired
  IntegralConfigService configService;

  @RequestMapping(value = "getConfig", method = RequestMethod.POST)
  @ApiOperation("获取所有的积分配置")
  public R getConfig() {
    try {
      //page.setGetAllRecord(false);	
      List<IntegralConfig> result = configService.getBaseMapper().selectList(new QueryWrapper<>());
      return R.ok().put("data",result);
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }

  @RequestMapping(value = "edit", method = RequestMethod.POST)
  @ApiOperation("编辑积分配置")
  public R getAllRecord(String jsonStr) {
    JSONArray jsonArray = JSONArray.parseArray(jsonStr);
    List<IntegralConfig> meetPricesList = new ArrayList<>();
    try {
      for (int i = 0; i < jsonArray.size(); i++) {
        // json转对象,提供的参数有:channelId;channelName;isall;time;size;vodStatus
        IntegralConfig price = jsonArray.getObject(i, IntegralConfig.class);
        meetPricesList.add(price);
      }
      configService.updateGrade(meetPricesList);
      return R.ok("修改成功");
    } catch (Exception e) {
      return R.error(e.getMessage());
    }
  }

  /**
   * 编辑图片上传
   *
   * @return
   */
  @RequestMapping(value = "uploadimg", method = RequestMethod.POST)
  @ApiOperation("配置图标上传")
  public R uploadImg(@RequestParam("file") MultipartFile file) {
    String result = null;
    if (file != null) {
      String fileName = UUID.randomUUID().toString() + file.getOriginalFilename()
        .substring(file.getOriginalFilename()
          .lastIndexOf("."), file.getOriginalFilename().length());
      result = UploadUtils.upload(UploadUtils.convertFile(file), fileName, FrogConstant.Path.INTEGRAL_CONFIG);
    }
    return R.ok(result);
  }
}
